package com.yy.yunpan.file.controller;

import com.yy.yunpan.common.result.Result;
import com.yy.yunpan.file.entity.File;
import com.yy.yunpan.file.service.FileService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 文件管理控制器
 *
 * @author YY
 * @since 2025-10-01
 */
@RestController
@RequestMapping("/api/file")
@Tag(name = "文件管理", description = "文件上传、下载、管理相关接口")
public class FileController {

    @Autowired
    private FileService fileService;

    /**
     * 获取当前登录用户ID
     */
    private Long getCurrentUserId() {
        return (Long) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    }

    @PostMapping("/upload-signature")
    @Operation(summary = "获取文件上传签名")
    public Result<Map<String, Object>> getUploadSignature(
            @RequestParam String fileName,
            @RequestParam Long fileSize,
            @RequestParam String contentType,
            @RequestParam(defaultValue = "0") Long parentId) {

        Long userId = getCurrentUserId();
        Map<String, Object> signature = fileService.getUploadSignature(userId, fileName, fileSize, contentType, parentId);
        return Result.success(signature);
    }

    @PostMapping("/save-metadata")
    @Operation(summary = "保存文件元数据")
    public Result<File> saveFileMetadata(
            @RequestParam String fileName,
            @RequestParam Long fileSize,
            @RequestParam String fileType,
            @RequestParam String ossKey,
            @RequestParam(defaultValue = "0") Long parentId,
            @RequestParam(required = false) String md5) {

        Long userId = getCurrentUserId();
        File file = fileService.saveFileMetadata(userId, fileName, fileSize, fileType, ossKey, parentId, md5);
        return Result.success(file);
    }

    @GetMapping("/list")
    @Operation(summary = "获取文件列表")
    public Result<Page<File>> getFileList(
            @RequestParam(defaultValue = "0") Long parentId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "20") Integer size,
            @RequestParam(defaultValue = "createTime") String orderBy,
            @RequestParam(defaultValue = "desc") String orderType) {

        Long userId = getCurrentUserId();
        Page<File> filePage = fileService.getFileList(userId, parentId, page, size, orderBy, orderType);
        return Result.success(filePage);
    }

    @PostMapping("/create-folder")
    @Operation(summary = "创建文件夹")
    public Result<File> createFolder(
            @RequestParam String folderName,
            @RequestParam(defaultValue = "0") Long parentId) {

        Long userId = getCurrentUserId();
        File folder = fileService.createFolder(userId, folderName, parentId);
        return Result.success(folder);
    }

    @PostMapping("/delete/{fileId}")
    @Operation(summary = "删除文件（移动到回收站）")
    public Result<Void> deleteFile(@PathVariable Long fileId) {
        Long userId = getCurrentUserId();
        fileService.deleteFile(userId, fileId);
        return Result.success();
    }

    @PostMapping("/rename/{fileId}")
    @Operation(summary = "重命名文件")
    public Result<File> renameFile(
            @PathVariable Long fileId,
            @RequestParam String newName) {

        Long userId = getCurrentUserId();
        File file = fileService.renameFile(userId, fileId, newName);
        return Result.success(file);
    }

    @PostMapping("/move/{fileId}")
    @Operation(summary = "移动文件")
    public Result<File> moveFile(
            @PathVariable Long fileId,
            @RequestParam Long targetParentId) {

        Long userId = getCurrentUserId();
        File file = fileService.moveFile(userId, fileId, targetParentId);
        return Result.success(file);
    }

    @GetMapping("/storage-info")
    @Operation(summary = "获取存储使用情况")
    public Result<Map<String, Object>> getStorageInfo() {
        Long userId = getCurrentUserId();
        Map<String, Object> storageInfo = fileService.getStorageInfo(userId);
        return Result.success(storageInfo);
    }

    @GetMapping("/recycle/list")
    @Operation(summary = "获取回收站文件列表")
    public Result<Page<File>> getRecycleFileList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "20") Integer size,
            @RequestParam(defaultValue = "updateTime") String orderBy,
            @RequestParam(defaultValue = "desc") String orderType) {

        Long userId = getCurrentUserId();
        Page<File> filePage = fileService.getRecycleFileList(userId, page, size, orderBy, orderType);
        return Result.success(filePage);
    }

    @PostMapping("/recycle/restore/{fileId}")
    @Operation(summary = "恢复回收站文件")
    public Result<File> restoreFile(@PathVariable Long fileId) {
        Long userId = getCurrentUserId();
        File file = fileService.restoreFile(userId, fileId);
        return Result.success(file);
    }

    @PostMapping("/recycle/delete/{fileId}")
    @Operation(summary = "彻底删除文件")
    public Result<Void> permanentDeleteFile(@PathVariable Long fileId) {
        Long userId = getCurrentUserId();
        fileService.permanentDeleteFile(userId, fileId);
        return Result.success();
    }

    @PostMapping("/recycle/clear")
    @Operation(summary = "清空回收站")
    public Result<Void> clearRecycleBin() {
        Long userId = getCurrentUserId();
        fileService.clearRecycleBin(userId);
        return Result.success();
    }

    @GetMapping("/download/{fileId}")
    @Operation(summary = "生成文件下载临时链接")
    public Result<Map<String, Object>> generateDownloadUrl(@PathVariable Long fileId) {
        Long userId = getCurrentUserId();
        Map<String, Object> downloadInfo = fileService.generateDownloadUrl(userId, fileId);
        return Result.success(downloadInfo);
    }

    @GetMapping("/preview/{fileId}")
    @Operation(summary = "生成文件预览临时链接")
    public Result<Map<String, Object>> generatePreviewUrl(@PathVariable Long fileId) {
        Long userId = getCurrentUserId();
        Map<String, Object> previewInfo = fileService.generatePreviewUrl(userId, fileId);
        return Result.success(previewInfo);
    }
}